1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package com.google.common.eventbus;
18
19 import static com.google.common.base.Preconditions.checkNotNull;
20
21 import com.google.common.base.Preconditions;
22
23 import java.lang.reflect.InvocationTargetException;
24 import java.lang.reflect.Method;
25
26 import javax.annotation.Nullable;
27
28
29
30
31
32
33
34
35
36
37
38
39
40 class EventSubscriber {
41
42
43 private final Object target;
44
45 private final Method method;
46
47
48
49
50
51
52
53 EventSubscriber(Object target, Method method) {
54 Preconditions.checkNotNull(target,
55 "EventSubscriber target cannot be null.");
56 Preconditions.checkNotNull(method, "EventSubscriber method cannot be null.");
57
58 this.target = target;
59 this.method = method;
60 method.setAccessible(true);
61 }
62
63
64
65
66
67
68
69
70
71 public void handleEvent(Object event) throws InvocationTargetException {
72 checkNotNull(event);
73 try {
74 method.invoke(target, new Object[] { event });
75 } catch (IllegalArgumentException e) {
76 throw new Error("Method rejected target/argument: " + event, e);
77 } catch (IllegalAccessException e) {
78 throw new Error("Method became inaccessible: " + event, e);
79 } catch (InvocationTargetException e) {
80 if (e.getCause() instanceof Error) {
81 throw (Error) e.getCause();
82 }
83 throw e;
84 }
85 }
86
87 @Override public String toString() {
88 return "[wrapper " + method + "]";
89 }
90
91 @Override public int hashCode() {
92 final int PRIME = 31;
93 return (PRIME + method.hashCode()) * PRIME
94 + System.identityHashCode(target);
95 }
96
97 @Override public boolean equals(@Nullable Object obj) {
98 if (obj instanceof EventSubscriber) {
99 EventSubscriber that = (EventSubscriber) obj;
100
101
102
103 return target == that.target && method.equals(that.method);
104 }
105 return false;
106 }
107
108 public Object getSubscriber() {
109 return target;
110 }
111
112 public Method getMethod() {
113 return method;
114 }
115 }